package com.demo.starter.exception;

import com.demo.starter.dto.GeneralResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * 全局Controller层异常处理类
 * @author cyj
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionResolver {

    /**
     * 校验单个对象不通过异常处理
     * @param exception MethodArgumentNotValidException
     * @return 统一返回对象
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GeneralResult validateException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        return GeneralResult.error(fieldError.getDefaultMessage());
    }

    /**
     * 校验集合数据不通过异常处理
     * @param exception ConstraintViolationException
     * @return 统一返回对象
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public GeneralResult constraintViolationException(ConstraintViolationException exception) {
        return GeneralResult.error(exception.getMessage());
    }

    /**
     * 请求参数转换异常处理
     * @param exception HttpMessageNotReadableException
     * @param request request对象
     * @return 统一返回对象
     */
    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public GeneralResult handleMessageNotReadableException(Exception exception, WebRequest request) {
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletWebRequest.getNativeRequest();

        log.error("请求参数序列化异常：url = {}", httpServletRequest.getRequestURI());
        log.error("请求参数序列化异常", exception);
        return GeneralResult.error(exception.getMessage());
    }
}
